import './style.scss';
import React, { Component } from 'react';
import { DIST } from 'conf';
import Tags from '../../common/Tags';
import Colors from '../../common/Color';
import Listbox from '../../common/Listbox';
import Pages from '../../common/Pages';
import { getImgs, getTypes } from '@/server/source';

export default class Index extends Component {

    constructor(props) {
        super(props);
        this.state = {
            tags: null,
            data: [],
            type: 10
        }
    }

    componentDidMount() {
        this.getTpys();
    }

    // 获取分类
    getTpys = () => {
        getTypes({type: 0}).then(res => {
            this.setState({
                tags: res.data.reverse()
            });
        });
    }

    // 分页
    getImgs = (num) => {
        return getImgs({
            type: this.state.type,
            pageSize: 20,
            pageNum: num || 1
        }).then(res => {
            if (res.success) {
                this.setState({
                    data: res.data
                });
                return res;
            }
        });
    }

    // 切换tags
    changeTags = e => {
        this.setState({
            type: e.id
        });
    }

    // 选择图片
    selectImg = elem => {
        UE.getEditor('container').focus();
        UE.getEditor('container').execCommand('inserthtml',`<img src="${elem.url}" />`);
    }

    render() {
        let { tags, data, type } = this.state;
        return (
            <div className="imgsource">
                <Tags data={tags} active={'主题'} onChange={this.changeTags} />
                <Listbox top={134}>
                    <div className="imgs">
                        <ul className="clearfix">
                            {
                                data.map( elem => {
                                    return (
                                        <li onClick={e => this.selectImg(elem)} key={elem.id}><img src={elem.url} /></li>
                                    )
                                })
                            }
                        </ul>
                    </div>
                </Listbox>
                <Pages key={type} ajax={this.getImgs} />
            </div>
        );
    }
}